import java.util.Arrays;
import java.util.HashMap;
import java.util.PriorityQueue;

public class L347 {

    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        int[] ints = new Solution().topKFrequent(nums, k);
        System.out.println(Arrays.toString(ints));
    }


    static class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            }

            PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2) -> pair1[1] - pair2[1]);

            map.forEach((key, v) -> {
                if (pq.size() < k) {
                    pq.add(new int[]{key, v});
                } else {
                    if (v > pq.peek()[1]) {
                        pq.poll();
                        pq.add(new int[]{key, v});
                    }
                }
            });
            int[] ints = new int[k];
            for (int i = 0; i < k; i++) {
                ints[i] = pq.poll()[0];
            }
            return ints;
        }
    }
}
